package me.zhengjie.spider.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.ReUtil;
import me.zhengjie.spider.common.SpiderConstant;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

public class SpiderUtil {


    private final static Long DEFAULT_MAX_SIZE = 1000L;

    public static String getFolderNameByNum(Long num) {
        return getFolderNameByNum(num, DEFAULT_MAX_SIZE);
    }

    public static String getFolderNameByNum(Long num, Long maxSize) {
        return String.valueOf((num / maxSize) + 1) + SpiderConstant.FOLDER_DIR + num;
    }

    /**
     *
     * @param playLink https://cdn.aqd-tv.com/video/7e3c9927/playlist/7e3c9927.m3u8
     * @param targetFile E:\\spider\\eladmin\\index.m3u8
     * @param tsName ts文件名匹配规则
     */
    public static void overwriteM3u8File(String playLink, String targetFile, String tsName) {
        File file = new File(playLink);
        String prePath = String.format("%s%s", file.getParentFile().getPath(), SpiderConstant.FOLDER_DIR);
        File localFile = new File(targetFile);
        if (!localFile.exists()) {
            return;
        }
        FileReader fileReader = new FileReader(targetFile);
        List<String> strings = fileReader.readLines();
        List<String> outputList = strings.stream().map(item -> {
            if (ReUtil.isMatch(tsName, item)) {
                item = prePath + item;
            }
            return item;
        }).collect(Collectors.toList());
        FileWriter writer = new FileWriter(targetFile);
        writer.writeLines(outputList);
    }
}
